/**
 * 绘制矩形
 */
const { L } = window;
const calcPolygonArea = () => 0;

export default class Rectangle {
  constructor(map, options) {
    Object.assign(this, {
      points: [],
      rectangle: null,
      redPtArr: [],
      tooltip: null,
      cancelMarker: null,
      id: null,
      bShowTooltip: false,
      bStartDrag: false,
      bDragReady: true,
      areaName: null,
      needLocation: false,
      _area: 0,
      ...options,
    });
    this.init(map);
  }

  init(map) {
    this.parent = {};
    this.map = map;
  }

  startDraw({ callback, mouseMoveCallback }) {
    this.clear();
    this.id = "rectangle_" + new Date().getTime();
    this.map.on("mousedown", this.onClick); // 点击地图
    this.map.on("mousemove", this.onMove); // 双击地图
    this.map.doubleClickZoom.disable(); // 禁用map双击事件
    this.map.dragging.disable();
    this.callback = callback;
    this.mouseMoveCallback = mouseMoveCallback;
  }

  stop() {
    this.map.off("click", this.onClick); // 点击地图
    this.map.off("mousemove", this.onMove); // 双击地图
    this.map.dragging.enable();
  }

  clear() {
    this.stop();
    this.rectangle && this.map.removeLayer(this.rectangle);
    this.rectangle = null;
    this.redPtArr.map((item) => this.map.removeLayer(item));
    this.redPtArr = [];
    this.tooltip && this.tooltip.remove();
    this.cancelMarker && this.map.removeLayer(this.cancelMarker);
    this.cancelMarker = null;

    this.points = [];
  }

  // map.off(....) 关闭该事件
  onClick = (e) => {
    L.DomEvent.stopPropagation(e); //阻止事件往map方向冒泡
    const redPt = L.circle(e.latlng, 1, {
      color: "#ff0000",
      fillColor: "ff0000",
      fillOpacity: 1,
    });
    this.points.push([e.latlng.lat, e.latlng.lng]);
    // this.map.addLayer(redPt);
    this.redPtArr.push(redPt);
  };

  onMove = (e) => {
    if (this.points.length > 0) {
      let points = [this.points[0], [e.latlng.lat, e.latlng.lng]]; //.map(([lat, lng]) => ({lat, lng}));
      points = L.rectangle(points).getLatLngs()[0];
      const area = calcPolygonArea(
        points.map((item) => {
          if (this.map.options.crs?.code === "shanghai2000") {
            const { lat, lng } = item;
            const [x, y] = COORDINATE_CONVERT_EXT.shcj_to_wgs84(
              lng,
              lat
            ).reverse();
            return { lat: y, lng: x };
          }
          return item;
        })
      );
      this._area = area;
      if (!this.maxArea || area < this.maxArea) {
        this.points[1] = [e.latlng.lat, e.latlng.lng];
        this.map.off("mousedown", this.onClick);
        this.map.on("mouseup", this.onFinish);
        this.rectangle && this.map.removeLayer(this.rectangle);
        this.rectangle = L.rectangle(this.points, {
          opacity: 1,
          color: "#32CEFF",
          fillOpacity: 0.6,
          fillColor: "#32CEFF",
        }).addTo(this.map);
        if (this.mouseMoveCallback) {
          this.mouseMoveCallback({
            points: this.points,
            rectangle: this.rectangle,
            area,
          });
        }
      }
    }
  };

  onFinish = (bSave = true) => {
    // this.addCancelBtn(new L.LatLng(...this.getCancelBtnPos()));
    this.rectangle && this.map.removeLayer(this.rectangle);
    this.rectangle = L.rectangle(this.points, {
      opacity: 1,
      color: "#32CEFF",
      fillOpacity: 0.6,
      fillColor: "#32CEFF",
    }).addTo(this.map);
    this.rectangle.on("click", () => {
      // this.tooltip.addTo(this.map);
      // this.setClickEvent(this.tooltip);
    });
    this.select();
    this.pointsBak = [...this.points];
    // 清除辅助图形
    this.points = [];
    this.stop();
    this.map.doubleClickZoom.enable(); // 禁用map双击事件
    this.map.dragging.enable();
    this.map.off("mouseup", this.onFinish);
    this.needLocation && this.map.fitBounds(this.rectangle.getBounds());
  };

  setTooltip = () => {
    if (this.bShowTooltip) {
      this.tooltip && this.map.removeLayer(this.tooltip);
      const { preventCircleMap, currentEditPreventId } = this.parent;
      const map = preventCircleMap.get(currentEditPreventId);
      map && map.eachLayer((item) => item._icon && item.closePopup());
      const tooltip = L.tooltip({
        direction: "top",
        permanent: true,
        interactive: true,
        noWrap: true,
        opacity: 0.9,
      });
      let selectedValue = "0";
      if (this.rectangle && this.rectangle.typeObj) {
        selectedValue = this.rectangle.typeObj.value;
      } else if (this.properties && this.properties.typeObj) {
        selectedValue = this.properties.typeObj.value;
      }
      const content = `<div class='preventCircle-rectangle'>
                      <select>
                        <option value='0' ${
                          selectedValue === "0" ? "selected" : ""
                        }>核心管控区</option>
                        <option value='1' ${
                          selectedValue === "1" ? "selected" : ""
                        }>重点控制区</option>
                        <option value='2' ${
                          selectedValue === "2" ? "selected" : ""
                        }>关注分流区</option>
                      </select>
                      <span class='preventCircle-rectangle-btn'>保存</span>
                    </div>`;
      tooltip.setContent(content);
      const points = [...this.rectangle._getMarkerLatLngs()];
      const latlng = points.sort((a, b) => b.lat - a.lat)[0];
      tooltip.setLatLng(latlng);
      tooltip.addTo(this.map);
      this.setClickEvent(tooltip);
      this.tooltip = tooltip;
    }
  };

  setClickEvent(tooltip) {
    const el = tooltip.getElement();
    el.addEventListener("click", (e) => L.DomEvent.stopPropagation(e));
    const bntSpan = el.getElementsByClassName("preventCircle-rectangle-btn")[0];
    bntSpan.removeEventListener("click", this.savePrevent);
    bntSpan.addEventListener("click", this.savePrevent);
    el.style.pointerEvents = "auto";
  }

  savePrevent = (e) => {
    L.DomEvent.stopPropagation(e); //阻止事件往map方向冒泡
    const parent = document.getElementsByClassName("preventCircle-rectangle");
    if (parent.length > 0) {
      const child = parent[0].getElementsByTagName("select");
      if (child.length > 0) {
        const value = child[0].value;
        const text = child[0].selectedOptions[0].text;
        this.rectangle.typeObj = { value, text };
      }
      this.select();
      this.parent.savePrevent(this.parent.currentEditPreventType, false);
      this.hideTooltip();
      // this.parent.bSavePrevent = false;
    }
    // this.map.removeLayer(this.tooltip);
  };

  hideTooltip() {
    this.tooltip && this.map.removeLayer(this.tooltip);
  }

  select(isClear = false) {
    if (this.parent.doRectangleSelect)
      this.parent.doRectangleSelect({
        points: this.points,
        rectangle: this.rectangle,
        isClear,
      });
    if (this.callback) {
      this.callback({
        points: this.points,
        rectangle: this.rectangle,
        area: this._area,
      });
    }
  }
}
